package controllers

import "LoginTemplate/models"

type CommunityController struct {
	BaseController
}

type Community struct {
	ID                 int     `json:"id"`
	CommunityName      string  `json:"community_name"`
	CommunityIntroduce string  `json:"community_introduce"`
	CommunityPrice     float64 `json:"community_price"`
	CommunityPicture   string  `json:"community_picture"`
	IsDe               int     `json:"is_de"`
}

// 添加社区
func (u *CommunityController) InsertCommunity() {
	var community Community
	err := u.ShouldBind(&community)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "insert into community ( community_name,community_introduce,community_price,community_picture ) values ( ? , ? ,?,? )"
	tx := models.DB.Debug().Exec(sql, community.CommunityName, community.CommunityIntroduce, community.CommunityPrice, community.CommunityPicture)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改社区
func (u *CommunityController) UpdateCommunity() {
	var community Community
	err := u.ShouldBind(&community)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "update community set community_name = ?,community_introduce = ?,community_price = ?,community_picture = ?,is_de = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, community.CommunityName, community.CommunityIntroduce, community.CommunityPrice, community.CommunityPicture, community.IsDe, community.ID)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type CommunityData struct {
	Code        int         `json:"code"`
	Msg         string      `json:"msg"`
	Data        []Community `json:"data"`
	Sum         int         `json:"sum"`         //总页数
	CurrentPage int         `json:"currentPage"` //当前页
	TotalNumber int         `json:"totalNumber"` //总条数
}

// 查询社区
func (u *CommunityController) SelectCommunity() {
	var pictureList PictureList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var community []Community
	sql := "select * from community where is_de = 0 limit ? , ?"
	tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&community)
	sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM community where is_de = 0"
	models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
	sqlNumBer := "select count(*) from community where is_de = 0"
	models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	if tx.Error != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var picturedata CommunityData
	picturedata.Code = 200
	picturedata.Data = community
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}
